package com.ken.common.web.http;

import com.ken.entity.base.protocol.R;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 处理响应体
 */
@ControllerAdvice
@ConditionalOnClass(ResponseHandler.class)
public class ResponseHandler implements ResponseBodyAdvice<R> {
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        if (R.class.isAssignableFrom(returnType.getMethod().getReturnType()))
            return true;
        return false;
    }

    @Override
    public R beforeBodyWrite(R body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {

        HttpStatus httpStatus = null;
        try {
            httpStatus = HttpStatus.valueOf(body.getCode());
        } catch (Exception e) {
            httpStatus = HttpStatus.valueOf(500);
        }
        //修改响应码 和 返回对象保存一致
        response.setStatusCode(httpStatus);
        //修改响应头 - 设置返回内容类型和编码
        response.getHeaders().set("Content-Type", "application/json;charset=utf-8");
        return body;
    }
}
